package org.jiucheng.magpiebridge.manager.controller.openapi.v1;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateUtils;
import org.jiucheng.ioc.annotation.Inject;
import org.jiucheng.magpiebridge.manager.dto.openapi.v1.LoginDto;
import org.jiucheng.magpiebridge.manager.dto.openapi.v1.Openapi;
import org.jiucheng.magpiebridge.manager.entity.SysUser;
import org.jiucheng.magpiebridge.manager.handler.RequestBody;
import org.jiucheng.magpiebridge.manager.handler.UncheckOpenapiHandler;
import org.jiucheng.magpiebridge.manager.out.OpenapiOut;
import org.jiucheng.magpiebridge.manager.util.JwtUtil;
import org.jiucheng.magpiebridge.manager.util.MD5Util;
import org.jiucheng.plugin.db.IBaseService;
import org.jiucheng.util.StringUtil;
import org.jiucheng.web.annotation.Controller;
import org.jiucheng.web.annotation.RequestMapping;
import org.jiucheng.web.annotation.RequestMethod;

@Controller(UncheckOpenapiHandler.class)
public class LoginController {
    
    @Inject
    private JwtUtil jwtUtil;
    @Inject
    private IBaseService baseService;
    
    @RequestMapping(value = "/openapi/v1/login", method = RequestMethod.POST, out = OpenapiOut.class)
    public Openapi login(@RequestBody LoginDto loginDto, HttpServletResponse res) {
        if (loginDto == null) 
            return Openapi.newInstance(1, "请求内容不能为空");
        if (StringUtil.isBlank(loginDto.getUsername()))
            return Openapi.newInstance(2, "邮箱不能为空");
        if (StringUtil.isBlank(loginDto.getPassword()))
            return Openapi.newInstance(3, "密码不能为空");
        SysUser sysUser = new SysUser();
        sysUser.setEmail(loginDto.getUsername());
        List<SysUser> sysUsers = baseService.list(sysUser);
        if (sysUsers == null || sysUsers.isEmpty())
            return Openapi.newInstance(4, "用户不存在");
        sysUser = sysUsers.get(0);
        if (!MD5Util.getMd5(loginDto.getPassword()).equalsIgnoreCase(sysUser.getPassword()))
            return Openapi.newInstance(5, "密码错误");
        if ("T".equals(sysUser.getInactive())) {
        	return Openapi.newInstance(6, "账号已停用");
        }
        Map<String, String> claims = new HashMap<String, String>();
        claims.put("gid", Long.toString(sysUser.getId()));
        claims.put("gemail", sysUser.getEmail());
        claims.put("isSuper", sysUser.getIsSuper());
        try {
            String token = jwtUtil.genToken(claims, DateUtils.addYears(new Date(), 10));
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            cookie.setMaxAge(-1);
            res.addCookie(cookie);
            return Openapi.newInstance(token);
        } catch (Exception e) {
            // e.printStackTrace();
            return Openapi.newInstance(4, "内部错误，请联系管理员");
        }
    }
}
